using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Gateway.IQuery.Sign;

namespace Gateway.UI.Api.Extensions.Middlewares;

/// <summary>
/// 滑动过期中间件
/// </summary>
public class SlidingExpirationMiddleware : IMiddleware
{
    private readonly ILogger<SlidingExpirationMiddleware> _logger;
    private readonly ITokenService _tokenService;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="logger"></param>
    /// <param name="tokenService"></param>
    public SlidingExpirationMiddleware(ILogger<SlidingExpirationMiddleware> logger, ITokenService tokenService)
    {
        _logger = logger;
        _tokenService = tokenService;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        try
        {
            if (context.Request.Path.Value.Contains("v1/chat/completions") ||
                context.Request.Path.Value.Contains("v1/images/generations") ||
                context.Request.Path.Value.Contains("v1/embeddings") ||
                context.Request.Path.Value.Contains("v1/video"))
            {
                await next(context);
                return;
            }

            string authorization = context.Request.Headers["Authorization"];
            if (!string.IsNullOrEmpty(authorization) && authorization.StartsWith("sk-"))
            {
                await next(context);
                return;
            }

            if (context.Response.HasStarted)
            {
                await next(context);
                return;
            }


            JwtSecurityToken token = null;
            if (!string.IsNullOrEmpty(authorization) && authorization.StartsWith("Bearer"))
            {
                if (authorization.Length > 6)
                {
                    token = new JwtSecurityTokenHandler().ReadJwtToken(authorization[7..]); // trim 'Bearer ' from the start
                }
            }
               

            if (token != null && token.ValidTo > DateTime.UtcNow)
            {
                TimeSpan timeElapsed = DateTime.UtcNow.Subtract(token.ValidFrom);
                TimeSpan timeRemaining = token.ValidTo.Subtract(DateTime.UtcNow);

                if (timeRemaining < timeElapsed)
                {
                    var userId = token.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value ??
                                 String.Empty;
                    var userName = token.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value ?? String.Empty;
                    context.Response.Headers.Append("Set-Authorization",
                        await _tokenService.CreateTokenAsync(userId, userName));
                }
            }
        }
        catch (Exception e)
        {
            _logger.LogError(e, "请求地址:" + context.Request.Path.Value + "," + e.Message);
        }

        await next(context);
    }
}